﻿using YL.NetCore.NetCoreApp;
using Microsoft.AspNetCore.Mvc;
using YL.Core.Dto;
using IServices;
using YL.Core.Entity.Fluent.Validation;
using YL.Core.Entity;
using System.Linq;
using NLog.LayoutRenderers;
using YL.Utils.Pub;
using YL.Utils.Extensions;
using Microsoft.AspNetCore.Authorization;
using SqlSugar;
using YL.Utils.Table;

namespace EduCMS.Controllers
{
    [Route("[controller]")]
    public class UserController : BaseController
    {
        private readonly IWhr_userServices _userServices;
        private readonly SqlSugarClient _client;
        public UserController(IWhr_userServices userServices, SqlSugarClient client) 
        {
            _userServices = userServices;
            _client = client;
        }

        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("register"), AllowAnonymous]       
        public IActionResult Register([FromForm]Whr_user dto) 
        {
            var validator = new UserFluent();
            var results = validator.Validate(dto);
            var success = results.IsValid;
            if (!success) 
            {
                string msg = results.Errors.Aggregate("", (current, item) => (current + item.ErrorMessage));
                return Json(new { code = PubEnum.Failed, msg });
            }
            var userInfo = _userServices.QueryableToEntity(u => u.Mobile == dto.Mobile);
            if (!userInfo.IsNull()) 
            {
                string msg = "此手机号已注册"; //添加到常量
                return Json(new { code = PubEnum.Failed, msg });
            }
            //Bcrypt密码
            var hashedPassword = BCrypt.Net.BCrypt.HashPassword(dto.Password);
            dto.Password = hashedPassword;
            bool flag = _userServices.Insert(dto);
            return Json(flag ? new { code = PubEnum.Success, msg = PubConst.Add1 } : new { code = PubEnum.Failed, msg = PubConst.Add2 });
        }

        [HttpGet("account")]
        public IActionResult AccountInfo() 
        {
            var userId = UserDto.UserId;
            var userCenterDto = _client.Queryable<Whr_wechat>().Select(u => new UserCenterDto
            {
                UserId = u.Id,
                Avatar = u.Avatar,           
                Add_date = u.AddTime
            }).Where($"id={userId}").First();
            
            return Json(Microprogram.DataInfo(PubEnum.Success, "", userCenterDto));
        }

        /// <summary>
        /// 更新地理位置
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("update_loaction")]
        public IActionResult UpdateLocation([FromForm] LocationDto dto) 
        {
            var user = _client.Queryable<Whr_user>().Where(u => u.UserId == UserDto.UserId).First();
            user.Latitude = dto.Latitude;
            user.Longitude = dto.Longitude;
            //以主键未更新条件
            var result = _client.Updateable(user).ExecuteCommand();
            if (result > 0) {
                return Json(Microprogram.DataInfo(PubEnum.Success, PubConst.Update1, new { id = result }));
            }
            return Json(Microprogram.DataInfo(PubEnum.Failed, PubConst.Update2, ""));
        }
    }
}